The Problem: You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
My Solution
function isOdd(num) {
return num % 2;
}
function getMiddle(str) {
const middleDigit = (str.length + 1) / 2;
if (isOdd(middleDigit) === 1) {
return str[middleDigit];
} else {
return str[middleDigit - 0.5] + str[middleDigit + 0.5];
}
}
console.log(getMiddle(`the`));
But i'm receiving a NaN output, rather than h , where has str[input] deviated from the my intention?
Thanks in advance!
Some annotations:
is....function isOdd(num) {
return num % 2 === 1;
}
function getMiddle(str) {
const middleDigit = Math.floor(str.length / 2);
return isOdd(str.length)
? str[middleDigit]
: str.slice(middleDigit - 1, middleDigit + 1);
}
console.log(getMiddle('the'));
console.log(getMiddle('boot'));
you are passing the wrong value to is_odd
function isOdd(num) {
return ((num % 2) === 1);
}
function getMiddle(str) {
const middleDigit = Math.floor(str.length / 2);
if (isOdd(str.length)) {
return str[middleDigit];
} else {
return str[middleDigit - 1] + str[middleDigit];
}
}
console.log(getMiddle(`they`));
Your execution was a little bit off!
function isOdd(num) {
return num % 2 === 1;
}
function getMiddle(str) {
if (isOdd(str.length)) {
return str[((str.length + 1) / 2) - 1];
} else {
return str[(str.length / 2) - 1] + str[str.length / 2];
}
}
console.log(getMiddle(`the`));
console.log(getMiddle(`root`));